package cn.com.seeederland.gkrpc.transport;

import cn.com.seederland.gkrpc.Peer;
import cn.com.seederland.gkrpc.common.constants.HttpProtocolConstants;
import cn.com.seederland.gkrpc.common.exception.HttpTransportException;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName HTTPTransportClient
 * @Author SighFate
 * @Date 2020/10/06 22:47
 * @Version 1.0
 * @Description HTTP请求客户端的实现
 */
public class HTTPTransportClient implements TransportClient {

    /**
     * 连接的服务器地址
     */
    private String url;

    @Override
    public void createConnection(Peer peer) {
        this.url = HttpProtocolConstants.HTTP_PROTOCOL + "://" + peer.getHost() + ":" + peer.getPort();
    }

    @Override
    public InputStream sendAndWaitResponse(InputStream data) {
        try {
            // 开启一个连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
            // 可以返回数据
            httpURLConnection.setDoOutput(HttpProtocolConstants.OUTPUT_SWITCH);
            // 可以读取数据
            httpURLConnection.setDoInput(HttpProtocolConstants.INPUT_SWITCH);
            // 不使用缓存
            httpURLConnection.setUseCaches(HttpProtocolConstants.CACHE_SWITCH);
            // 请求数据使用的方式
            httpURLConnection.setRequestMethod(HttpProtocolConstants.HTTP_METHOD);
            // 开始连接
            httpURLConnection.connect();

            // 将请求的数据复制到需要连接的输出流中
            IOUtils.copy(data, httpURLConnection.getOutputStream());
            // 获取请求状态码
            int resultCode = httpURLConnection.getResponseCode();
            if (resultCode == HttpURLConnection.HTTP_OK) {
                // 请求成功，状态码为200，返回结果流数据
                return httpURLConnection.getInputStream();
            } else {
                // 非成功，输出错误流
                return httpURLConnection.getErrorStream();
            }
        } catch (IOException e) {
            throw new HttpTransportException(e);
        }
    }

    @Override
    public void closeConnection() {

    }
}
